import React, { useEffect, useRef, useState } from 'react'
import { Card, Col, Row , List,Drawer  } from 'antd';
import {EllipsisOutlined} from '@ant-design/icons';
import { Avatar} from 'antd';
const { Meta } = Card;
import axios from 'axios';
import * as echarts from 'echarts';
import  _ from 'lodash'

export default function Home() {
  const {username,region,role:{roleName}} = JSON.parse(localStorage.getItem("token"));
  const [dataSource,setDataSource]=useState([])
  useEffect(()=>{
    const getDataSource=async()=>{
      // jsonserver处理数据 这里我用前端来处理数据
      // http://localhost:3000/news?publishState=2&_sort=view&_order=desc&_limit=6
      let data= (await axios.get("http://localhost:3000/news?publishState=2")).data
      setDataSource(data.map((item)=>{
        return {
          title:item.title,
          star:item.star,
          view:item.view,
          id:item.id,
          key:item.id
        }
      }))
    }
    getDataSource()
  },[])
  const viewData=dataSource.sort((a,b)=>b.view-a.view).slice(0,6)
  const starData=dataSource.sort((a,b)=>b.star-a.star).slice(0,6)


  //可视化柱状图所需数据
  const ref=useRef(null)
  const renderBarView=(obj)=>{
      // 检查是否已经存在 ECharts 实例，如果存在则先销毁
      if (ref.current && ref.current.echartsInstance) {
        ref.current.echartsInstance.dispose();
      }
      
      var myChart = echarts.init(ref.current);
      // 将实例保存到 DOM 元素上，以便后续清理
      ref.current.echartsInstance = myChart;
      
      // 指定图表的配置项和数据
      var option = {
        title: {
          text: '新闻分类图示'
        },
        tooltip: {},
        legend: {
          data: ['数量']
        },
        xAxis: {
          data:Object.keys(obj),
          axisLable:{
            rotate:45,
            interval:0
          }
        },
        yAxis: {
          minInterval:1
        },
        series: [
          {
            name: '数量', 
            type: 'bar',
            data:Object.values(obj).map(item=>item.length)
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);

      window.onresize =  ()=> { 
        myChart.resize();
      }
  }  
  useEffect(()=>{
    const fetchData = async () => {
      try {
        const res = await axios.get("http://localhost:3000/news?publishState=2&_expand=category");        
        // 使用loadsh中的数据分组功能 将数据根据新闻分类名称进行分组
        const groupedData = _.groupBy(res.data, item => item.category.title);
        renderBarView(groupedData);
      } catch (error) {
        console.error("Failed to fetch data:", error);
      }
    };

    fetchData();

    // 清理函数：在组件卸载时销毁 ECharts 实例
    return () => {
      // 清除resize事件监听 监听浏览器窗口尺寸变动的
       window.onresize=null
     }
  },[])

 
  /* 控制抽屉组件 包裹饼状图 */
  // 可视化饼状图所需数据与渲染
  const cakeRef=useRef(null)
  const [pieData,setPieData]=useState([])
  const [open, setOpen] = useState(false);
  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };
  //饼状图
  const renderCakeView=(arrData)=>{
    // 确保 DOM 元素存在再初始化图表
    if (cakeRef.current) {
      var myChart = echarts.init(cakeRef.current);
      var option = {
        title: {
          text: '个人新闻数据',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: arrData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    }
  }
  
  // 修改 useEffect，添加 open 状态作为依赖
  useEffect(()=>{
     const fetchData = async () => {
      try {
        const res = await axios.get(`http://localhost:3000/news?author=${username}&publishState=2&_expand=category`);        
        // 使用loadsh中的数据分组功能 将数据根据新闻分类名称进行分组
        const groupedData = _.groupBy(res.data, item => item.category.title);
        console.log(groupedData);
        const arrData = Object.values(groupedData).map(item => ({
          name: item[0].category.title,
          value: item.length
        }));
        setPieData(arrData)
        // 只有当 Drawer 打开时才初始化
        if (open) {
          renderCakeView(pieData)
        }
      } catch (error) {
        console.error("Failed to fetch data:", error);
      }
    };
    fetchData();
  },[open])
  return (
    <div>
      <Row gutter={16}>
        <Col span={8}>
          <Card title="用户最长浏览" variant="borderless">
              <List
                bordered
                dataSource={viewData}
                renderItem={item => (
                  <List.Item>
                    <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                  </List.Item>
                )}
              />
          </Card>
        </Col>
        <Col span={8}>
          <Card title="用户喜欢最多" variant="borderless">
              <List
                bordered
                dataSource={starData}
                renderItem={item => (
                  <List.Item>
                    <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                  </List.Item>
                )}
              />
          </Card>
        </Col>
        <Col span={8}>
          <Card
           variant="borderless"
            cover={
              <img
                draggable={false}
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <EllipsisOutlined key="ellipsis" onClick={()=>showDrawer()}/>,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=8" />}
              title={username}
              description={
                <div>
                  <b>{region}</b>
                  <b> </b>
                  <b>{roleName}</b>
                </div>
              }
            />
          </Card>
        </Col>
      </Row>
      <div id='main1' style={{
        height: '400px',
      }} ref={ref}>
      </div>
      <Drawer
        width={'500px'}
        title="个人新闻数据展示"
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
         <div id='main2' style={{
        height: '400px',
          }} ref={cakeRef}>
        </div>
      </Drawer>
    </div>
  )
}
